package com.wcs.spring.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.github.pagehelper.PageInfo;

public class PageTag<T> extends TagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7038530055149452018L;

	public static int PAGE_SIZE = 5; // 每页大小

	public static int MAX_PAGE_INDEX = 5;// 最多显示5个数字连接

	private String url;

	private PageInfo<T> page;

	public String getUrl() {
		return this.url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
		// 获取分页bean
		// PageInfo<T> page = (PageInfo<T>) request.getAttribute("page");

		JspWriter out = this.pageContext.getOut();
		// 拼接分页信息
		StringBuilder s = new StringBuilder();
		s.append("<table class=\"gridtable\" style=\"width:100%;text-align: center;\"><tr>");
		if (page.isHasPreviousPage()) {
			s.append("<td><a href=\"" + url + "?pageNum=" + page.getPrePage() + "&pageSize=" + page.getPageSize()
					+ "\">前一页</a></td>");
		}

		// for(int i=0;i<page.getNavigatepageNums().length;i++){
		//
		// }
		for (int nav : page.getNavigatepageNums()) {
			if (nav == page.getPageNum()) {
				s.append("<td style=\"font-weight: bold;\">" + nav + "</td> ");
			}
			else {
				s.append("<td><a href=\"" + url + "?pageNum=" + nav + "&pageSize=" + page.getPageSize() + "\">" + nav
						+ "</a></td>");
			}
		}

		if (page.isHasNextPage()) {
			s.append("<td><a href=\"" + url + "?pageNum=" + page.getNextPage() + "&pageSize=" + page.getPageSize()
					+ "\">前一页</a></td>");
		}
		s.append("<td>共 " + page.getPages() + " 页&nbsp;" + page.getTotal() + "条</td>");

		try {
			out.println(s.toString());
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		return SKIP_BODY;
	}
}
